<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <el-input v-model="deptQuery" prefix-icon="Search" placeholder="部门名称"/>

                <el-tree
                        ref="treeRef"
                        v-model="queryParams.deptId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        highlight-current
                        default-expand-all
                        :expand-on-click-node="false"
                        :filter-node-method="filterDeptNode"
                        @node-click="handleDeptNodeClick"
                />
            </el-col>
            <!--用户数据-->
            <el-col :span="20" :xs="24">
                <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="用户昵称" prop="nickName">
                        <el-input
                                v-model="queryParams.nickName"
                                placeholder="请输入用户昵称"
                                clearable
                                @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="账号" prop="userName">
                        <el-input
                                v-model="queryParams.userName"
                                placeholder="请输入账号"
                                clearable
                                @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="状态 " prop="status">
                        <el-select v-model="queryParams.status" placeholder="请选择状态 " clearable>
                            <el-option
                                    v-for="dict in sys_normal_disable"
                                    :key="dict.value"
                                    :label="dict.label"
                                    :value="dict.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                                type="primary"
                                plain
                                icon="Plus"
                                @click="handleAdd"
                                v-hasPermi="['system:user:add']"
                        >新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                                type="success"
                                plain
                                icon="Edit"
                                :disabled="single"
                                @click="handleUpdate"
                                v-hasPermi="['system:user:edit']"
                        >修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                                type="danger"
                                plain
                                icon="Delete"
                                :disabled="multiple"
                                @click="handleDelete"
                                v-hasPermi="['system:user:remove']"
                        >删除
                        </el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center"/>
                    <el-table-column label="编码" align="center" prop="id"/>
                    <el-table-column label="账号" align="center" prop="userName"/>
                    <el-table-column label="用户昵称" align="center" prop="nickName"/>
                    <el-table-column label="手机号" align="center" prop="phone" width="110"/>
                    <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip/>
                    <el-table-column label="角色" align="center" prop="roles" min-width="100">
                        <template #default="scope">
                            <template v-if="scope.row.roles">
                                <el-tag v-for="(item, index) in scope.row.roles" :key="index" size="small">{{ item.roleName }}
                                </el-tag>
                            </template>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="性别" align="center" prop="sex">
                        <template #default="scope">
                            <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态 " align="center" prop="status">
                        <template #default="scope">
                            <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
                    <el-table-column label="操作" align="center" fixed="right" width="150"
                                     class-name="small-padding fixed-width">
                        <template #default="scope">
                            <el-button
                                    v-if="!scope.row.admin"
                                    type="primary"
                                    text
                                    icon="Edit"
                                    @click="handleUpdate(scope.row)"
                                    v-hasPermi="['system:user:edit']"
                            >修改
                            </el-button>
                            <el-button
                                    v-if="!scope.row.admin"
                                    type="danger"
                                    text
                                    icon="Delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['system:user:remove']"
                            >删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                        v-show="total>0"
                        :total="total"
                        v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize"
                        @pagination="getList"
                />
            </el-col>
        </el-row>

        <!-- 添加或修改系统用户对话框 -->
        <el-dialog :title="title" v-model="open" width="700px" append-to-body>
            <el-form v-if="open" ref="userRef" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="用户昵称" prop="nickName">
                            <el-input v-model="form.nickName" placeholder="请输入用户昵称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="登录账号" prop="userName">
                            <el-input v-model="form.userName" placeholder="请输入登录账号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="!form.id">
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="form.password" type="password" show-password placeholder="请输入密码"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属部门" prop="deptId">
                            <el-tree-select
                                    v-model="form.deptId"
                                    :data="deptOptions"
                                    :props="{ value: 'id', label: 'label', children: 'children' }"
                                    value-key="id"
                                    placeholder="请选择部门"
                                    check-strictly
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="角色" prop="roleIds">
                            <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                                <el-option
                                        v-for="item in roleOptions"
                                        :key="item.id"
                                        :label="item.roleName"
                                        :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户性别" prop="sex">
                            <el-select v-model="form.sex" placeholder="请选择性别">
                                <el-option
                                        v-for="dict in sys_user_sex"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态 " prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                        v-for="dict in sys_normal_disable"
                                        :key="dict.value"
                                        :value="dict.value"
                                >{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="User">
import {listUser, getUser, delUser, addUser, updateUser} from "@/api/system/user";
import {treeSelect} from "@/api/system/dept";
import {listRole} from "@/api/system/role";
import {getCurrentInstance, reactive, ref, toRefs, watch} from "vue";

const {proxy} = getCurrentInstance();
const {sys_user_sex, sys_normal_disable} = proxy.initDict('sys_user_sex', 'sys_normal_disable');

const userList = ref([]);
const deptOptions = ref([]);
const roleOptions = ref([]);
const deptQuery = ref("");
const treeRef = ref();
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        nickName: null,
        userName: null,
        status: null
    },
    rules: {
        nickName: [
            {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        phone: [
            {required: true, message: "手机号不能为空", trigger: "blur"}
        ],
        userName: [
            {required: true, message: "登录账号不能为空", trigger: "blur"}
        ],
        password: [
            {required: true, message: "用户密码不能为空", trigger: "blur"}
        ],
        deptId: [
            {required: true, message: "部门不能为空", trigger: "change"}
        ],
        roleIds: [
            {required: true, message: "角色不能为空", trigger: "blur"}
        ],
        sex: [
            {required: true, message: "性别不能为空", trigger: "change"}
        ],
        status: [
            {required: true, message: "用户状态不能为空", trigger: "change"}
        ]
    }
});

const {queryParams, form, rules} = toRefs(data);

// 根据名称筛选部门树
watch(deptQuery, (val) => {
    treeRef.value.filter(val);
})

getList();
getDeptTreeSelect();
getRoleList();

/** 查询系统用户列表 */
function getList() {
    loading.value = true;
    listUser(queryParams.value).then(response => {
        userList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

/** 查询部门树下拉列表 */
function getDeptTreeSelect() {
    treeSelect().then(response => {
        deptOptions.value = response.data;
    });
}

/** 查询角色列表 */
function getRoleList() {
    listRole({pageNum: 1, pageSize: 100}).then(response => {
        roleOptions.value = response.rows;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        remark: null,
        deptId: null,
        nickName: null,
        userName: null,
        password: null,
        phone: null,
        sex: null,
        roleIds: [],
        status: "0",
    };
    proxy.resetForm("userRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.value.deptId = null;
    proxy.resetForm("queryRef");
    handleQuery();
}

//部门筛选过滤
function filterDeptNode(value, data) {
    if (!value) return true;
    return data.label.includes(value);
}

//点击部门节点事件
function handleDeptNodeClick(data, node) {
    queryParams.value.deptId = data.id;
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加系统用户";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value
    getUser(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改系统用户";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["userRef"].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateUser(form.value).then(response => {
                    proxy.$message.success("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addUser(form.value).then(response => {
                    proxy.$message.success("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$messageBox.confirm('是否确认删除系统用户编号为"' + _ids + '"的数据项？').then(function () {
        return delUser(_ids);
    }).then(() => {
        getList();
        proxy.$message.success("删除成功");
    }).catch(() => {
    });
}

</script>
